from django.shortcuts import render

# Create your views here.

from django.views.decorators.http import require_POST, require_GET
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, JsonResponse
from datetime import datetime, timedelta
from .utils import csp


def index(request):
    return HttpResponse(b'hello world!')


def get_data(request):
    data = {
        "name": "张三",
        "age": 18
    }
    response = JsonResponse(data)

    # 设置 Cookie
    max_age = 365 * 24 * 60 * 60  # One year
    expires = datetime.strftime(
        datetime.utcnow() + timedelta(seconds=max_age),
        "%a, %d-%b-%Y %H:%M:%S GMT"
    )
    response.set_cookie(
        key="sessionid",
        value="2hccie27gdzd5bxy18yles9ovfc4ksdf",
        expires=expires,
        path='/app01',
        httponly=True
    )

    response.set_cookie(
        key="id",
        value="123456",
        path='/app01',
    )

    return response


def check_cookie(request):
    cookie_by_id = request.COOKIES.get('id')
    cookie_by_sessionid = request.COOKIES.get('sessionid')
    res = {
        "cookie_by_id": cookie_by_id,
        "cookie_by_sessionid": cookie_by_sessionid
    }

    return JsonResponse(res)


# 白名单中，包含jquery网址
CSP_POLICY_CONTAIN_JQ = "default-src 'self'; script-src 'self' https://code.jquery.com; " \
                        "style-src 'self' http://127.0.0.1:8000/"

# 白名单中，不包含jquery网址
CSP_POLICY_NOT_JQ = "default-src 'self'; script-src 'self'; style-src 'self' " \
                    "http://127.0.0.1:8000/"


@csp.set_csp(CSP_POLICY_NOT_JQ)
def csp_test(request):
    """
    添加了csp的响应头
    :param request:
    :return:
    """
    return render(request, 'csp.html')


@csrf_exempt
# @require_POST
def post_test(request):
    return JsonResponse({"code": 0, "message": "success", "data": 123})
